﻿/*  CamHelper (See http://camhelper.codeplex.com/ or https://bitbucket.org/AndiKS/camhelper for more Info)
    Copyright (C) 2011 Andreas Wimmer

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

using System;
using System.IO;
using System.Windows.Forms;
using CamHelper.Facade.TopSolid.Interfaces;
using SystemWrapper.IO;

namespace CamHelper.Engine
{
    public class TopSolidApplication : ITopSolidApplication
    {
        public ITSApplication ComApplication { get; private set; }

        private IFileWrap _file;

        public TopSolidApplication(ITSApplication app, IFileWrap file)
        {
            ComApplication = app;
            _file = file;
        }

        public bool IsDocumentOpen()
        {
            return ComApplication.Documents.Count > 0;
        }

        public ITopSolidDocument GetCurrentDocument()
        {
            ITSDocument doc;

            try
            {
                doc = ComApplication.CurrentDocument;
            }
            catch (Exception ex)
            {
                throw new CurrentDocumentNotFoundException(ex);
            }

            return new TopSolidDocument(doc, _file);
        }

        public void Message(string msg)
        {
            string path = Path.Combine(Application.StartupPath, "Macro\\Message.lob");
            if (!_file.Exists(path))
                throw new TopSolidMacroNotFoundException(path);

            ComApplication.PushStringOnStack(msg);
            ComApplication.ExecuteMacroKeepStack(path);
        }

        public void Dispose()
        {
            ComApplication.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}
